#!/bin/bash
# dnsupdate - update the DNS and DOMAIN NAME by novell-ipsec-tools.
#
# Bin Li (bili@novell.com)

# don't need any stdout
exec >/dev/null
exec 2>/dev/null

# /var/tmp/dnscfg provide the DNS and DOMAIN NAME.
# such as
#
# NOT_SET_DNS=0 or 1
# PRIMARY_DNS=2.2.3.4
# SECONDARY_DNS=4.5.6.7
# DOMAIN_NAME=lab.test.a
source /var/tmp/dnscfg

RESOLVCONF=/etc/resolv.conf

# When use the NM connect the VPN, we shouldn't set the DNS
# The NM will take over it.
if [ $NOT_SET_DNS -eq 1 ]; then
	exit 0
fi

# the header in /etc/resolv.conf
CONFBEGIN=" ### /etc/resolv.conf file autogenerated by racoon
of novell-ipsec-tools!\n# Process id: $PPID \n###"

# the dnsupdate is up when connect successfully.
if [ $1 = "up" ]; then
	if [ -f $RESOLVCONF ]; then
		NOT_SAVE=`cat $RESOLVCONF | grep novell-ipsec-tools`
		if [ -z "$NOT_SAVE" ]; then
			# Backup the previous configuration
			cp $RESOLVCONF $RESOLVCONF.ipsec.save
		fi
	fi

	echo -e $CONFBEGIN > $RESOLVCONF

	cat $RESOLVCONF.ipsec.save | grep -v ^# >> $RESOLVCONF

	if [ -n $DOMAIN_NAME ]; then
		# The  domain  and search keywords are mutually exclusive
		FIND_DOM=`cat $RESOLVCONF | grep $DOMAIN_NAME`
		if [ -z "$FIND_DOM" ]; then
			KEY_SEARCH=`cat $RESOLVCONF | grep search`
			if [ -n "$KEY_SEARCH" ]; then
				sed -i "/search/s/$/ $DOMAIN_NAME/" $RESOLVCONF
				FLAG=1
			fi
			KEY_DOMAIN=`cat $RESOLVCONF | grep domain`
			if [ -n "$KEY_DOMAIN" ]; then
				sed -i "/domain/s/$/ $DOMAIN_NAME/" $RESOLVCONF
				FLAG=1
			fi

			# we don't fond the keyword, add new
			if [ $FLAG -ne 1 ]; then
				echo "search $DOMAIN_NAME" >> $RESOLVCONF
			fi
		fi
	fi

	if [ -n "$PRIMARY_DNS" ]; then
		FIND_PRI=`cat $RESOLVCONF | grep $PRIMARY_DNS`
		if [ -z "$FIND_PRI" ]; then
			echo "nameserver $PRIMARY_DNS" >> $RESOLVCONF
		fi
	fi

	if [ -n "$SECONDARY_DNS" ]; then
		FIND_SEC=`cat $RESOLVCONF | grep $SECONDARY_DNS`
		if [ -z "$FIND_SEC" ]; then
			echo "nameserver $SECONDARY_DNS" >> $RESOLVCONF
		fi
	fi
fi

if [ $1 = "down" ]; then
	if [ -f $RESOLVCONF.ipsec.save ]; then
		cp $RESOLVCONF.ipsec.save $RESOLVCONF
	fi
fi
